import React, { useState } from 'react';
import { View, Text, Button, Image, StyleSheet, ActivityIndicator } from 'react-native';
import { colorizeImage } from './services/api';
import * as ImagePicker from 'expo-image-picker';

export default function App() {
  const [image, setImage] = useState<string | null>(null);
  const [coloredImage, setColoredImage] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const pickImage = async () => {
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    if (!result.canceled) {
      setImage(result.assets[0].uri);
      setColoredImage(null);
    }
  };

  const handleColorize = async () => {
    if (!image) return;
    
    setLoading(true);
    try {
      const response = await colorizeImage(image);
      setColoredImage(`data:image/png;base64,${response.image}`);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Manga Colorizer</Text>
      
      <Button title="Pick an image" onPress={pickImage} />
      
      {image && (
        <>
          <View style={styles.imageContainer}>
            <Text>Original Sketch:</Text>
            <Image source={{ uri: image }} style={styles.image} />
          </View>
          
          <Button 
            title="Colorize" 
            onPress={handleColorize} 
            disabled={loading}
          />
        </>
      )}
      
      {loading && <ActivityIndicator size="large" />}
      
      {coloredImage && (
        <View style={styles.imageContainer}>
          <Text>Colored Result:</Text>
          <Image source={{ uri: coloredImage }} style={styles.image} />
        </View>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  imageContainer: {
    marginVertical: 20,
    alignItems: 'center',
  },
  image: {
    width: 300,
    height: 300,
    resizeMode: 'contain',
    marginTop: 10,
  },
});
